﻿using System;
using System.Data;
using System.Data.Entity;
using System.Linq;
using LuckyLoot.Common.Repositories.Contracts;

namespace LuckyLoot.Common.Repositories
{
    public class Repository<TEntity, TContext> : IRepository<TEntity>, IDisposable
        where TEntity : class
        where TContext : DbContext, new()
    {
        private TContext _context = new TContext();
        public TContext Context
        {
            get { return _context; }
            set { _context = value; }
        }

        public TEntity GetById(int id)
        {
            return Context.Set<TEntity>().Find(id);
        }

        public virtual IQueryable<TEntity> GetAll()
        {
            IQueryable<TEntity> query = Context.Set<TEntity>();
            return query;
        }

        public IQueryable<TEntity> GetByCriteria(System.Linq.Expressions.Expression<Func<TEntity, bool>> criteria)
        {
            try
            {
                IQueryable<TEntity> query = Context.Set<TEntity>().Where(criteria);
                return query;
            }
            catch (Exception)
            {
                return null;
            }
        }

        public virtual void Add(TEntity entity)
        {
            Context.Set<TEntity>().Add(entity);
        }

        public virtual void Delete(TEntity entity)
        {
            Context.Set<TEntity>().Remove(entity);
        }

        public virtual void Edit(TEntity entity)
        {
            Context.Entry(entity).State = EntityState.Modified;
        }

        public virtual void Save()
        {
            Context.SaveChanges();
        }


        #region IDisposable Members

        public void Dispose()
        {
            Context.Dispose();
        }

        #endregion
    }
}
